<?php

namespace App\Models\User;

use App\Http\Controllers\Controller;
use App\Http\Controllers\PCHController;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;


/**
 * App\Models\User\LiveUser
 *
 * @property int $id
 * @property string $user_name 用户名
 * @property int $user_coin 用户余额
 * @property float $user_score 积分
 * @property string $user_password 密码
 * @property int $user_sex 1=男2=女
 * @property string $user_phone 用户手机号
 * @property string $user_avatar 用户头像
 * @property string $user_token token
 * @property string $invite_code 邀请码
 * @property string $vip_no 会员ID
 * @property int $is_vip 是否会员 0 不是 1 是
 * @property int $vip_dead_line 会员到期时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereInviteCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereIsVip($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserAvatar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserCoin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserPassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserPhone($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserScore($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereUserToken($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereVipDeadLine($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\LiveUser whereVipNo($value)
 * @mixin \Eloquent
 */
class LiveUser extends Model
{
    public $table = 'live_user';
    public $timestamps = false;

    public function getLastLoginAttribute($val)
    {
        return $val ? date('Y-m-d H:i:s',$val) : 0;
    }

    public function getCreatedTimeAttribute($val)
    {
        return date('Y-m-d H:i:s',$val);
    }

    public function getVipDeadLineAttribute($val)
    {
        if (!empty($val)) {
            $val = date('Y-m-d H:i:s',$val);
        } else {
            $val = '';
        }
        return $val;
    }

    public function getUserCountAttribute()
    {
        if ($this->is_agent == 1) {
            return self::query()->where('invite_user_id','=',$this->id)->count();
        } else {
            return 0;
        }
    }

    #获取用户列表
    public static function getUserList($start_time,$end_time,$search,$is_agent)
    {
        $data = self::query()
            ->when(!empty($start_time) && !empty($end_time), function ($query) use ($start_time, $end_time) {
                return $query->whereBetween('created_time', [Carbon::parse($start_time)->startOfDay(), Carbon::parse($end_time)->endOfDay()]);
            })
            ->where(function ($query) use($search) {
                $query->when($search !== '' && $search !== null, function ($query) use($search) {
                    return $query->where('id', 'like', "%{$search}%")->orWhere('user_name', 'like', "%{$search}%");
                });
            })
            ->where('is_agent','=',$is_agent)
            ->select('id','user_name','user_score','user_phone','user_avatar','is_vip','vip_dead_line','is_agent','invite_code','status','last_login','created_time')->orderByDesc('created_time')
            ->paginate(15);
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #根据代理ID获取下级用户列表
    public static function getUserListByAgentId($id)
    {
        $data = self::query()->where('invite_user_id','=',$id)->select('id','user_name','user_score','user_phone','user_avatar','is_vip','vip_dead_line','is_agent','invite_code','status','last_login','created_time')->orderByDesc('created_time')->paginate(15);
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #根据用户ID获取联系方式
    public static function getPhoneByUserId(int $user_id)
    {
        $phone = self::query()->where('id','=',$user_id)->value('user_phone');
        return $phone;
    }

    #根据用户ID修改状态
    public static function changeStatusById(int $id, int $status)
    {
        $flag = self::query()->where('id','=',$id)->update([
                    'status' => $status,
                ]);
        return $flag;
    }

    #根据用户ID删除用户
    public static function deleteUserById(int $id)
    {
        $flag = self::query()->where('id','=',$id)->delete();
        return $flag;
    }

    #根据用户名获取用户
    public static function getUserByUserName(string $user_name)
    {
        $user = self::query()->where('user_name','=',$user_name)->first();
        if (empty($user)){
            return false;
        }else{
            return $user;
        }
    }

    #根据邀请码获取邀请人ID
    public static function getUserIDByInviteCode(string $invite_code)
    {
        $user_id = self::query()->where('invite_code','=',$invite_code)->value('id');
        if (empty($user_id)){
            return false;
        }else{
            return $user_id;
        }
    }

    #根据id获取用户
    public static function getUserByUserId($user_id)
    {
        $user = self::query()->find($user_id);
        return $user;
    }

    #创建一个新的用户
    public static function createUser($input)
    {
        #过滤表中不存在的字段
        $input = Controller::createData('live_user',$input);
        #密码加密
        $input['user_password'] = Controller::mkPass($input['user_password']);
        #生成用户
        $user_id  = self::query()->insertGetId($input);
        if ($user_id) {
            return $user_id;
        }
        return false;
    }

    #根据用户ID更新用户信息
    public static function updateUser(int $id, $input)
    {
        #过滤表中不存在的字段
        $input = Controller::createData('live_user',$input);
        #密码加密
        if (empty($input['user_password'])) {
            unset($input['user_password']);
        } else {
            $input['user_password'] = Controller::mkPass($input['user_password']);
        }
        $flag = self::query()->where('id','=',$id)->update($input);
        return $flag;
    }

    #更新token
    public static function UpdateToken(int $user_id,$ip)
    {
        /*$user   = LiveUser::getUserByUserId($user_id);
        if ($user) {
            $user = $user->toArray();
        } else {
            return false;
        }*/
        $token      = Controller::Token($user_id,$ip);
        $flag       = self::query()->where('id','=',$user_id)->update([
                        'user_token' => $token,
                        'last_login' => time(),
                    ]);
        if ($flag !== false) {
            $key = PCHController::getUserTokenByUserId($user_id);
            Redis::setex($key,3600*24*365,$token);
            return $token;
        } else {
            return false;
        }
    }

    #统计下级代理数量
    public static function countUserAgent(int $user_id)
    {
        $count = self::query()->where('invite_user_id','=',$user_id)->count();
        return $count;
    }

    #修改密码
    public static function modifyPassword(int $user_id,$user_password)
    {
        $user_password = Controller::mkPass($user_password);
        $flag = self::query()->where('id','=',$user_id)->update(['user_password'=>$user_password]);
        return $flag;
    }

    #修改个性签名
    public static function modifySign(int $user_id, $sign)
    {
        $flag = self::query()->where('id','=',$user_id)->update(['user_sign' => $sign]);
        return $flag;
    }

    #修改联系方式
    public static function modifyPhone(int $user_id, $phone)
    {
        $flag = self::query()->where('id','=',$user_id)->update(['user_phone' => $phone]);
        return $flag;
    }

    #自增或自减积分  type=1 自增  type=2 自减
    public static function modifyScore(int $user_id, int $score, int $type)
    {
        if ($type == 1) {
            $flag = self::query()->where('id','=',$user_id)->increment('user_score',$score);
        } else {
            $flag = self::query()->where('id','=',$user_id)->decrement('user_score',$score);
        }
        return $flag;
    }

    #开下级代理
    public static function openAgent(int $user_id, $phone, $invite_code)
    {
        $flag = self::query()->where('id','=',$user_id)->update([
                    'user_phone'    => $phone,
                    'is_agent'      => 1,
                    'invite_code'   => $invite_code,
                ]);
        return $flag;
    }

    /**
     * 开会员 会员续费 二合一
     * @param int $user_id
     * @param int $how_long  秒
     * @return int
     */
    public static function addVipTime(int $user_id, int $how_long)
    {
        $flag = self::query()->where('id','=',$user_id)->update([
                    'vip_dead_line' => $how_long,
                    'is_vip'        => 1,
                ]);
        return $flag;
    }
}
